<?php

namespace App\Services;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Request;
use Jedrzej\Pimpable\PimpableTrait;

trait MyPimpableTrait
{
    use PimpableTrait;

    /**
     * 重写方法，添加模糊搜索字段
     *
     * Enable searchable, sortable and withable scopes
     *
     * @param Builder $builder query builder
     * @param array $query
     */
    public function scopePimp(Builder $builder, $query = [], $sort = [], $relations = [])
    {
        $query = Arr::except($query ?: Request::all(), [$this->sortParameterName, $this->withParameterName]);

        // 处理模糊搜索的字段
        array_filter($this->vague, function ($item) use (&$query) {
            if (in_array($item, array_keys($query))) {
                $query[$item] = "%{$query[$item]}%";
            }
            return $query;
        });

        $builder->filtered($query)->sorted($sort)->withRelations($relations);
    }
}